__author__ = 'tyrion'

from  conf.gloal import PLUGIN_TYPE
from  conf.gloal import CONFIG_CENTER_SERVER
from  common.tools.httpd import GetHttpRequest

import json

def GetInstancesDetail(SvrName):
    #use svr name get instances
    print("info: get instances in svr = %s" % SvrName)

    url = "http://%s/infrastructure-console/server/get/%s" %(CONFIG_CENTER_SERVER, SvrName)
    print("info: %s" % url)
    ret = GetHttpRequest(url)
    # print(ret)
    if ret[0] == "":
        return  "error: no instance in this server"

    if ret[1] != 200:
        return "error"

    try:
        jsonRet = json.loads(ret[0])
    except IndexError :
        return "error"
    # print(jsonRet)
    ipList = jsonRet.get("network").get("ip")
    try:
        myIp = ipList[3]
    except IndexError:
        return "error"

    instances = jsonRet.get("instance")
    # print(instances)

    myInstances = []
    tmpInstance = {}
    for instance in instances:
        tmpInstance["type"] = instance.get("type")
        tmpInstance["hostname"] = instance.get("serverName")
        tmpInstance["instancename"] = instance.get("name")
        tmpInstance["ip"] = myIp
        tmpInstance["port"] = instance.get("custom")
        myInstances.append(tmpInstance)

    # ports = ""
    # for i in range(8080, 8105):
    #     tmp = "  %d"%i
    #     ports+=tmp
    #
    # print( ports)
    # instances = [{"type":"tomcat", "hostname": "flexweb-wx-1", "ip":"221.228.81.134", "ports": ports},\
    #     {"type":"tomcat", "hostname": "flexweb-wx-2", "ip":"221.228.81.135", "ports": ports},\
    #     {"type":"tomcat", "hostname": "flexweb-wx-3", "ip":"221.228.81.137", "ports": ports},\
    #     {"type":"tomcat", "hostname": "flexweb-wx-4", "ip":"221.228.81.138", "ports": ports}, \
    #     {"type":"tomcat", "hostname": "flexweb-wx-5", "ip":"221.228.81.157", "ports": ports}]
    # # ret = "tomcat"
    # return instances
    print(myInstances)
    return  myInstances


def GetPluginType(url):
    print("info : get plugin type")
    print("info: url = %s"%url)
    ret = GetHttpRequest(url)
    print("info: ret =%s" % ret)
    return  PLUGIN_TYPE


if __name__ == "__main__":
    GetInstancesDetail("flexweb-wx-1")